package com.codejiwei.flink.sql;

import com.codejiwei.flink.entity.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

/**
 * @author jiwei
 * @description
 * @date 2023/5/25 13:52
 */
public class Flink_SQL_BaseUse {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(3);
        DataStreamSource<WaterSensor> waterSensorStream =
                env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 6000L, 60));

        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        // 使用sql查询未注册的表
        //1.流转换成表
        Table inputTable = tEnv.fromDataStream(waterSensorStream);
        //2.执行查询
        Table resultTable = tEnv.sqlQuery("select * from " + inputTable + " where id = 'sensor_1'");
        //3.表转换成流
        tEnv.toDataStream(resultTable, Row.class).print();

        env.execute();
    }
}
